package com.zhs.gccs.mbtiles;

import android.content.Context;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MbtilesDbManager {

    private volatile static MbtilesDbManager mbtilesDbManager;
    private volatile Context mContext;
    private volatile Map<String,DbManager> dbManagers;


    private MbtilesDbManager(Context context) {
        this.mContext = context;
        this.dbManagers = new HashMap<>();
    }

    public void reloadDb(String dbDir,String dbName){
        try {
            DbManager dbManager = getDbManager(dbDir,dbName);
            dbManager.close();
            dbManagers.remove(dbName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static MbtilesDbManager getInstance(Context context) {
        if (mbtilesDbManager == null) {
            synchronized (MbtilesDbManager.class) {
                if (mbtilesDbManager == null) {
                    mbtilesDbManager = new MbtilesDbManager(context);
                }
            }
        }
        return mbtilesDbManager;
    }

    public DbManager getDbManager(String dbDir,String dbName) {
        DbManager dbManager = dbManagers.get(dbDir+"/"+dbName);
        if(dbManager==null){
            dbManager = initDbManager(dbDir,dbName);
        }
        return dbManager;
    }

    private DbManager initDbManager(String dbDir,String dbName) {
        try {
            DbManager.DaoConfig config = new DbManager.DaoConfig()
                    .setDbDir(new File(dbDir))//new File(Utils.getMainPath(mContext)))
                    .setDbName(dbName+".db");
            DbManager dbManager = x.getDb(config);
            dbManagers.put(dbName,dbManager);
            return dbManager;
        } catch (DbException e) {
            e.printStackTrace();
            return null;
        }
    }
}
